package blogwork;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class blog_body
 */
@WebServlet("/blog_body")
public class blog_body extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public blog_body() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		
		Map<String, Object> resultMap =new LinkedHashMap<>();
		// 1.建立SQL连接
		Connection conn = null ;
		try {
			conn = DBUtils.getConnection();
			conn.setAutoCommit(false);

			// 2.执行SQL语句

			response.setCharacterEncoding("utf-8");
//			response.setContentType("text/json; charset=UTF-8");
			response.setContentType("application/json;  charset=UTF-8");
			
			String selectSQL = "select  blog.id, blog.author_id,register.avt,blog.title,blog.publish_time from blog left join register on register.id=blog.author_id order by blog.publish_time desc";
		//	System.out.println(selectSQL);
			PreparedStatement pstmt = conn.prepareStatement(selectSQL);
			ResultSet result = pstmt.executeQuery();
			int i=1;
			while(result.next()){
				resultMap.put("id"+i, result.getInt("id"));
				resultMap.put("avt"+i, result.getString("avt"));
				resultMap.put("title"+i, result.getString("title"));
				resultMap.put("publish_time"+i, result.getString("publish_time"));
				i++;
			}
			conn.commit();
			result.close();
			pstmt.close();
			conn.close();
		} catch (SQLException sqlE) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		System.out.println(resultMap);	
		PrintWriter out = response.getWriter();
		out.append(JSON.toJSONString(resultMap));
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
